import { middleLogger } from '@/utils/back/devlogger';
import { pathsToRegs } from '@/utils/common';
import { NextRequest, NextResponse } from 'next/server';

/* 
use new domain urls:
// ------------- from google docs ------------- //
Retailer portal (legacy)	https://www.my-company.net.cn/rsds/*
Admin portal	https://www.my-company.net.cn/index.php/_admin/*
Mailchimp webhook	https://www.my-company.net.cn/monkey/webhook/*

*/

const rmHtmlSuffixPaths = ['/new-arrivals.html', '/promotion.html'];
const redirectPaths = [
  '/rsds(/?$|/.*|\\?.*)',
  '/rsdropship(/?$|/.*|\\?.*)',
  '/_admin',
  '/index.php',
  '/monkey/webhook(/?$|/.*|\\?.*)',
];

export default function redirectMiddleware(req: NextRequest, next: Fn) {
  const pathname = req.nextUrl.pathname;
  const rmHtmlSuffixRegs = pathsToRegs(rmHtmlSuffixPaths);
  if (rmHtmlSuffixRegs.some(reg => reg.test(pathname))) {
    middleLogger.info('redirectMiddleware', 'rm .html suffix', pathname);

    return NextResponse.redirect(new URL(req.url.replace(/\.html/, '')));
  }

  const redirectNewDomainResponse = (domain: string) => {
    const url = pathname + req.nextUrl.search;
    return NextResponse.redirect(new URL(url, domain));
  };

  const redirectRegs = pathsToRegs(redirectPaths);
  if (redirectRegs.some(reg => reg.test(pathname))) {
    middleLogger.info('redirectMiddleware', 'jump to new domain', pathname);
    return redirectNewDomainResponse(process.env.NEXT_PUBLIC_DSZ_DOMAIN!);
  }

  return next(req);
}
